import Taro, { Component, useRouter } from '@tarojs/taro';
import {
  View,
  Swiper,
  SwiperItem,
  Image,
  WebView,
} from '@tarojs/components';
import './index.scss';
import { bannerList, bannerRich } from '../../services/program';
import NavigationBar from '../../components/navigationBar/index';
import { fullImgUrl, timeFormat, getQueryString } from '../../utils/utils';
import { getCardInfo, getUserInfo, } from '../../services/user';
import TipBanner from '../../components/tip-banner/index.js';

import MultiTextModal from '../../components/multi-text-modal/index';
import { activeCard, addCard } from '../../services/card';
import { shareList } from '../../services/electronicCard';
import IconScan from '../../static/home/scan.png';
import homename from '../../static/public/home_name.png';
import IconGoods from '../../static/home/goods.png';
import IconDingzhi from '../../static/home/dingzhi.png';
import IconUser from '../../static/home/user.png';
import TabBar from '../../components/tab-bar/index';

export default class Index extends Component {
  config = {
    navigationBarTitleText: '中鹿岛',
  };

  state = {
    userInfo: Taro.getStorageSync('userInfo') || null,
    list: [],
    isShowWebView: false,
    webViewUrl: '',
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    isShowModal: false,
    isTipsModa: Taro.getStorageSync('setting').is_home_tip,
    isTipBanner: true,
    contentArr: null,
    cardInfo: null,
    modalTitle: '',
    nowIdx: 0,
    swiperH: '',
    comfirmText: '',
    cancleText: '',
    tabsList: [
      { icon: IconScan, text: '首页', type: 'scan' },
      { icon: IconGoods, text: '商场', type: 'shop' },
      { icon: IconScan, text: '扫码提货', type: 'scan' },
      { icon: IconDingzhi, text: '定制', type: 'custom' },
      { icon: IconUser, text: '我的', type: 'user' },
    ],
    rich: '',
    statusS: 1,
  };

  componentWillMount() {
    this.getBannerList();
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() {
  }
  componentDidShow() {
    if (this.$router.params.q) {
      const q = decodeURIComponent(this.$router.params.q);
      console.log(q)

      const new_card_no = getQueryString(q, 'new_card_no');
      if (!new_card_no) {
        const card_no = getQueryString(q, 'card_no');
        if (!card_no) {
          const agent_id = getQueryString(q, 'agent_id');
          if (agent_id) {
            Taro.setStorageSync('agent_id', agent_id);
            if (Taro.getStorageSync('userInfo')) {
              Taro.redirectTo({
                url: "/subPackageWork/pages/agent_customizes/index"
              })
            }
          } else {
            const coupon_no = getQueryString(q, 'goods_coupon_no');
            Taro.setStorageSync('coupon_no', coupon_no);
            if (Taro.getStorageSync('userInfo')) {
              Taro.redirectTo({
                url: "/subPackageWork/pages/coupon-exchange/index"
              })
            }
          }
        } else {
          Taro.setStorageSync('card_no_home', card_no);
          if (Taro.getStorageSync('userInfo')) {
            Taro.redirectTo({
              url: "/subPacKagebWork/pages/bangdingcard/index"
            })
          }
        }
      } else {
        Taro.setStorageSync('bindding_card_no', new_card_no);
        if (Taro.getStorageSync('userInfo')) {
          Taro.redirectTo({
            url: "/subPacKagebWork/pages/bindingcard/index"
          })
        }
      }
    } else {
      Taro.removeStorageSync('card_no_home')
      Taro.removeStorageSync('bindding_card_no')
      Taro.removeStorageSync('agent_id')
      Taro.removeStorageSync('coupon_no')
    }
    // if (this.$router.params) {
    //   console.log(this.$router.params);
    //   let { type, card_id, initiator_id } = this.$router.params

    //   console.log(type);
    //   if (type == 'electornic-card') {
    //     // const card_id = getQueryString(q, 'card_id');
    //     // const initiator_id = getQueryString(q, 'initiator_id');
    //     shareList().then(res => {
    //       Taro.setStorageSync('shareList', res.list);
    //       let pathUrl = `/subPackageWork/pages/electronic-lp/index?card_id=${card_id}&initiator_id=${initiator_id}`;
    //       Taro.redirectTo({
    //         url: pathUrl
    //       })
    //     })

    //   }
    // }

    if (typeof this.$scope.getTabBar === 'function' && this.$scope.getTabBar()) {
      this.$scope.getTabBar().$component.setState({
        selected: 0
      })
    }
    this.setState(
      {
        userInfo: Taro.getStorageSync('userInfo') || null,
      },
      () => {
        if (this.state.userInfo) {
          getUserInfo({
            id: this.state.userInfo.id + '',
          }).then(res => {
            Taro.setStorageSync('userInfo', res);
            this.setState({
              userInfo: res,
            });
          });
        }
      }
    );
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  getBannerList() {
    const userInfo = Taro.getStorageSync('userInfo');
    var list = []
    bannerList().then(res => {
      res.forEach(element => {
        element.cover = fullImgUrl(element.cover);
        if (userInfo.member_level == element.member_level || element.member_level == 3) {
          list.push(element)
        }
      });
      this.setState({
        list: list,
      });
    });
    bannerRich().then(res => {
      res = res.replace(/\<img/gi, '<img style="width: 100% !important; class="rich-img"');
      this.setState({
        rich: res,
      });
    });
  }

  onShareAppMessage() {
    let setting = Taro.getStorageSync('setting');
    return {
      title: `${setting.share_title}`,
      path: '/pages/home/index',
      imageUrl: `${fullImgUrl(setting.share_img)}`,
    };
  }

  scan = () => {

    // Taro.setStorageSync('card_no', '00200820000017192')
    // Taro.navigateTo({
    //   url: `/subPackageWork/pages/exchange/index?type=coupon`
    // })
    // return
    if (!this.state.userInfo) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/login/index',
      });
    } else {
      let self = this;
      Taro.scanCode({
        onlyFromCamera: true,
        success(res) {
          if (res.result.slice(0, 2) === '00') {
            Taro.setStorageSync('card_no', res.result);
            Taro.navigateTo({
              url: `/subPackageWork/pages/exchange/index?type=coupon`,
            });
          } else {
            getCardInfo({
              card_no: res.result.trim(),
            }).then(data => {
              if (data.status === 6) {
                Taro.setStorageSync('card_no', data.card_no);
                if (data.user) {
                  Taro.setStorageSync('barcode_address', data.user.level_customize_pic);
                } else {
                  Taro.setStorageSync('barcode_address', '');
                }
                Taro.setStorageSync('attr_name', data.attr_name);
                Taro.navigateTo({
                  url: `/subPackageWork/pages/exchange/index`,
                });
              } else if (data.status === 4) {
                addCard({
                  card_no: data.card_no,
                }).then(
                  res => {
                    Taro.showToast({
                      title: '添加成功',
                      icon: 'none',
                    });
                    // 二级代理从一级代理领卡
                    let contentArr = [
                      {
                        key: '卡号',
                        value: data.card_no,
                      },
                      {
                        key: '类型',
                        value: data.attr_name,
                      },
                    ];
                    self.setState({
                      contentArr: contentArr,
                      isShowModal: true,
                      cardInfo: data,
                      modalTitle: '已加入我的兑换卡',
                      comfirmText: '继续添加',
                      cancleText: '关闭',
                    });
                  },
                  () => {
                    this.setState({
                      isShowModal: false,
                    });
                  }
                );
              } else if (data.status === 5) {
                let contentArr = [
                  {
                    key: '卡号',
                    value: data.card_no,
                  },
                  {
                    key: '类型',
                    value: data.attr_name,
                  },
                ];
                self.setState({
                  contentArr: contentArr,
                  isShowModal: true,
                  cardInfo: data,
                  modalTitle: '兑换卡',
                  comfirmText: '去付款',
                  cancleText: '取消',
                });
              } else {
                // Taro.showToast({
                //   title: '卡的状态不对',
                //   icon: 'none'
                // })
              }
            });
          }
        },
      });
    }
  };

  shopping = () => {
    var userInfo = Taro.getStorageSync('userInfo')
    if (userInfo.member_level > 0) {
      Taro.redirectTo({
        url: '/pages/vip-list/index',
      });
    } else {
      Taro.navigateTo({
        url: `/subPackageWork/pages/goods-list/index`,
      });
    }
  };

  customized = () => {
    Taro.navigateTo({
      url: `/subPackageWork/pages/customized/index?id=1&showBtn=1`,
    });
  };

  goUser = () => {
    Taro.navigateTo({
      url: '/subPacKagebWork/pages/bangdingcard/index',
    });
  };

  bannerClickHandler(banner) {
    if (banner.type === 1) {
      // 链接
      // this.setState({
      //   isShowWebView: true,
      //   webViewUrl: banner.url
      // })
      Taro.navigateTo({
        // url: `/subPackageWork/pages/web-view/index?url=${banner.url}`
        url: `/subPackageWork/pages/webView/index?url=${banner.url}`,
      });
    } else if (banner.type === 2) {
      // 商品详情
      Taro.navigateTo({
        url: `/pages/goods-detail/index?id=${banner.goods_id}`,
      });
    } else if (banner.type === 3) {
      // 定制
      Taro.navigateTo({
        url: `/subPackageWork/pages/customizeds/index?id=${banner.article_id}`,
      });
    } else if (banner.type == 5) {
      this.scan()
    } else if (banner.type == 4) {
      Taro.navigateTo({
        url: banner.url,
      });
    } else if (banner.type == 6) {
      Taro.navigateTo({
        // url: `/subPackageWork/pages/web-view/index?url=${banner.url}`
        url: `/subPacKagebWork/pages/vidioplay/index?video_id=${banner.video_id}`,
      });
    }

    // if (banner.name === "绑卡入会") {
    //   // 链接
    //   // this.setState({
    //   //   isShowWebView: true,
    //   //   webViewUrl: banner.url
    //   // })
    //   this.goUser();

    //   // Taro.navigateTo({
    //   //   // url: `/subPackageWork/pages/web-view/index?url=${banner.url}`
    //   //   url: `/subPackageWork/pages/webView/index?url=${banner.url}`,
    //   // });
    // } else if (banner.name === "会员商城") {
    //   // this.shopping();

    //   // 商品详情
    //   // Taro.navigateTo({
    //   //   url: `/pages/goods-detail/index?id=${banner.goods_id}`,
    //   // });
    //   this.shopping();

    // } else if (banner.name === '专属定制') {

    //   this.customized();
    //   // 定制
    //   // Taro.navigateTo({
    //   //   url: `/subPackageWork/pages/customized/index?id=${banner.article_id}`,
    //   // });
    // }
  }

  outStorage() {
    Taro.navigateTo({
      url: `/subPackageWork/pages/choose-agency/index`,
    });
  }

  enterStorage() {
    Taro.navigateTo({
      url: `/subPackageWork/pages/storage-success/index?type=0`,
    });
  }

  cancleCb() {
    this.setState({
      isShowModal: false,
    });
  }

  confirmCb() {
    if (this.state.cardInfo.status === 4 && this.state.userInfo.level !== 0) {
      this.setState(
        {
          isShowModal: false,
        },
        () => {
          this.scan();
        }
      );
    } else if (this.state.cardInfo.status === 5) {
      activeCard({
        card_no: this.state.cardInfo.card_no,
        pay_type: 3,
        pay_platform: 1,
      }).then(data => {
        Taro.requestPayment({
          ...JSON.parse(data.payload).metadata,
        }).then(
          data => {
            this.setState(
              {
                isShowModal: false,
              },
              () => {
                Taro.navigateTo({
                  url: `/subPackageWork/pages/apply-success/index`,
                });
              }
            );
          },
          data => {
            this.setState(
              {
                isShowModal: false,
              },
              () => {
                Taro.navigateTo({
                  url: `/pages/my-order/index`,
                });
              }
            );
          }
        );
      });
    }
  }

  tabItemClickCb(item) {
    // Taro.navigateTo({
    //   url: item.url,
    // });
  }
  static defaultProps = {
    nowIdx: 0,
    swiperH: '',
  };
  //获取swiper高度
  getHeight = (e) => {
    var winWid = Taro.getSystemInfoSync().windowHeight - this.state.navigationBarHeight//获取当前屏幕的宽度
    var imgh = e.detail.height;//图片高度
    var imgw = e.detail.width;//图片宽度
    var sH = winWid * imgh / imgw + "px"
    this.setState({
      swiperH: imgh //设置高度
    }, () => {
    })
  }
  close = () => {
    this.setState({
      isTipsModa: false,
      isTipBanner: false,
    });
  };
  //swiper滑动事件
  swiperChange = (e) => {
    this.setState({
      nowIdx: e.detail.current
    })
  }
  render() {
    const {
      isShowModal,
      contentArr,
      modalTitle,
      userInfo,
      comfirmText,
      list,
      isTipsModa,
      isTipBanner,
      isShowWebView,
      webViewUrl,
      navigationBarHeight,
    } = this.state;
    return (
      <View className='home' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar />
        {/* {isTipsModa == 1 && <TipsModal onClose={this.close}></TipsModal>} */}
        {isTipBanner && <TipBanner onClose={this.close}></TipBanner>}
        {isTipBanner && <View className='home_tip_banner_shadow'></View>}
        {isShowModal && (
          <MultiTextModal
            title={modalTitle}
            confirmText={comfirmText}
            contentArr={contentArr}
            cancleCb={this.cancleCb.bind(this)}
            confirmCb={this.confirmCb.bind(this)}
          />
        )}
        {isShowWebView && <WebView src={webViewUrl} />}
        <View className="CH"><Image mode='widthFix' className='luzhongdao-image' src={homename} /></View>
        <Swiper
          onChange={this.swiperChange}
          next-margin="90rpx"
          previous-margin="90rpx"
          className='banner'
          indicatorColor='#DDD'
          indicatorActiveColor='#B2B2B2'
          circular
          autoplay={!isTipBanner}
        >
          {list.map((banner, index) => {
            return (
              <SwiperItem
                className="swiper-d"
                key={banner.id}
                onClick={() => {
                  this.bannerClickHandler(banner);
                }}
              >
                <View style={`background-image: url(${fullImgUrl(banner.cover)})`} className={`swiper-img ${this.state.nowIdx === index ? "swiper-active" : ""}`}></View>
                {/* <Image onLoad={this.getHeight} style={`height:${this.state.swiperH}`} className={`swiper-img ${this.state.nowIdx === index ? "swiper-active" : ""}`} src={banner.cover} /> */}
                <View onClick={() => {
                  this.tabItemClickCb(banner);
                }} className="description" style="text-align:center">{banner.name}     <Image mode='scaleToFill' className='banner-image' /></View>
              </SwiperItem>
            );
          })}
        </Swiper>
        <View className="tabBar" >
          <TabBar statusS={this.state.statusS}></TabBar>
        </View>

      </View>
    );
  }
}
